﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PDFWriter
{
    public class PDFEngine : INode
    {
        const string DOCUMENT = "Document";
        const string VERSION = "version";
        const string TRAILER = "trailer";
        
        private string xmlString = "";
        private XmlDocument reader = new XmlDocument();
        private List<PDFObject> generatedObject = new List<PDFObject>();
        public PDFEngine(string xmlString)
        {
            this.xmlString = xmlString;
            reader.LoadXml(xmlString);
        }

        public PDFEngine()
        {
            reader.LoadXml(xmlString);
        }
        private string ProcessXML()
        {
            foreach (XmlNode node in reader.FirstChild.ChildNodes)
            {
                generatedObject.AddRange(Utility.GetPDFObjects(node.OuterXml));
            }

            string generationID = null;
            string versionID = "%PDF-";
            if (reader.FirstChild.Name == DOCUMENT)
            {
                if (reader.FirstChild.Attributes[VERSION] != null)
                {
                    versionID += reader.FirstChild.Attributes[VERSION].Value;
                }                
            }
            generatedObject.Insert(0, new PDFObject() { Text = versionID, ObjectType = VERSION });            
            string pageTrailer = GetPageTrailer(GetDocumentCatalog(generatedObject));
            PDFObject trailerObject = new PDFObject() { Text = pageTrailer, ObjectType = TRAILER};
            generatedObject.Add(trailerObject);
            return pageTrailer;
        }

        private string GetPageTrailer(string parameters)
        {
            StringBuilder trailerStrin = new StringBuilder();
            trailerStrin.Append("trailer\n<<\n/Root "+parameters+"\n"+">>");
            return trailerStrin.ToString();
        }

        private string GetDocumentCatalog(List<PDFObject> pdfObject)
        {
            foreach (PDFObject item in pdfObject)
            {
                if ( item.ObjectType == PDFCatalog.CATALOG_TAG)
                {
                    return item.ObjectID;
                }
            }
            return null;
        }


        #region INode Members

        public PDFObject GetPDFObject()
        {
            return new PDFObject() { Text = ProcessXML(), ObjectType = TRAILER};
        }

        public List<PDFObject> GetPDFObjects()
        {
            ProcessXML();
            return generatedObject;
        }

        #endregion
    }
}
